package com.atguigu.flink.chapter2;

import org.apache.flink.api.common.typeinfo.Types;
import org.apache.flink.api.java.ExecutionEnvironment;
import org.apache.flink.api.java.operators.*;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.util.Collector;

/**
 * @Author lizhenchao@atguigu.cn
 * @Date 2020/12/18 10:34
 */
public class Flink02_WC_Batch_Lambda {
    public static void main(String[] args) throws Exception {
        // 1. 获取批次处理的执行环境
        ExecutionEnvironment benv = ExecutionEnvironment.getExecutionEnvironment();
        // 2. 读取数据
        DataSource<String> source = benv.readTextFile("input/words.txt");
        // 3. 各种转换处理
        FlatMapOperator<String, String> wordsFLO = source
          .flatMap((String value, Collector<String> out) -> {
              String[] split = value.split(" ");
              for (String word : split) {
                  out.collect(word);
              }
          })
          .returns(Types.STRING);

        MapOperator<String, Tuple2<String, Long>> wordAndOne = wordsFLO
          .map(value -> Tuple2.of(value, 1L))
          .returns(Types.TUPLE(Types.STRING, Types.LONG));

        UnsortedGrouping<Tuple2<String, Long>> wordOneGrouped = wordAndOne.groupBy(0);

        AggregateOperator<Tuple2<String, Long>> result = wordOneGrouped.sum(1);
        // 4. 控制台输出
        result.print();

    }
}
